<?php
/**
 *  TinyMVC - TinyMVCRegistry.class.php file
 * 
 * @author Adrian Wieczorek <adi(at)tinymvc(dot)org>
 * @package TinyMVC
 * @version $Id: TinyMVCRegistry.class.php 7 2007-09-12 22:09:47Z adi3ek $
 * 
 */

/**
 * Registry singleton class to keep configuration data
 * @package TinyMVC
 */  
class TinyMVCRegistry {
	private $values = array();
	private $configs = array();
	static private $instance = null;
    
	private function __construct() {
 }
  
	private function __clone() {
	}

	/**
	 * get class instance
	 * @return Registry
	 */
	static public function getInstance() {
		if(self::$instance == null) {
		  self::$instance = new TinyMVCRegistry;    	
		}
		return self::$instance;
	}

	/**
	 * set config value
	 * @param string $configName config name
	 * @param string $value	config value 
	 */
	private function setValue($configName, $value) {
		if(is_array($value)) {
			foreach($value as $key => $val) {
		 	$this->values[$configName . '_' .$key] = $val;
			}    		
		
			// store all config for getValues() method
  	$this->configs[$configName] = $value;    		
  }
  else {
			$this->values[] = $value;
  }
 }

	/**
	 * get value from config
	 * @param string $key config name key (eg: ConfigName_KeyName)
	 * @return mixed config value
	 */
	public function getValue($key) {
		return isset($this->values[$key]) ? $this->values[$key] : false;
	}
  
	/**
	 * get all values for given config
	 * @param string $configName config name
	 * @return array config values
	 */
	public function getValues($configName) {
		return isset($this->configs[$configName]) ? $this->configs[$configName] : false;
	} 
		  
	/**
	 * load config from file, $configName array must de declared in config file.
	 * @param string $configName config file name
	 */
	public function loadConfig($configName) {
		if(defined('TINYMVC_PROJECT_CONFIG_PATH')) {
			$configFilePath = TINYMVC_PROJECT_CONFIG_PATH . '/' . $configName . '.php';
			if(file_exists($configFilePath)) {
				require_once($configFilePath);
	   if(is_array(${$configName})) {
	   	$this->setValue($configName, ${$configName});   	
	   }
	   else {
	   	throw new TinyMVCException("Array: $configName not found in config file.");
	   }
				
				return $this->getValues($configName);
			}
			else {
				throw new TinyMVCException("Config file: $configFilePath - not found.");
			}
		}
		else {
			throw new TinyMVCException("undefined TINYMVC_PROJECT_CONFIG_PATH");
		}
	}
}
